﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Coldairarrow.DotNettyRPC;
using ZooKeeperManage.Helper;

namespace ZooKeeperManage.Dispersed
{

    public class ServerData
    {
        public List<string> Ip { get; set; }
        public int Port { get; set; }
    }

    /// <summary>
    /// 分布式服务
    /// </summary>·
    public class DispersedServer
    {

        private readonly int _port;
        /// <summary>
        /// rpc服务
        /// </summary>
        private readonly RPCServer _rPcServer;

        private readonly List<WorkServer> _workServerS;

        // private Dictionary<string, object> Data { get; set; } = new Dictionary<string, object>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="port">监听端口</param>
        public DispersedServer(int port)
        {
            _port = port;
            _rPcServer = new RPCServer(_port);
            _workServerS = new List<WorkServer>();
        }

        public void RegisterService<TIService, TService>() where TService : class, TIService where TIService : class
        {
            _rPcServer.RegisterService<TIService, TService>();
            var work = new WorkData()
            {
                Name = typeof(TIService).Name,
                Data = new ServerData()
                {
                    Ip = Network.GetIPv4AddressList(),
                    Port = _port
                }.ToJson()
            };
            _workServerS.Add(new WorkServer(work));

        }

        public void Start()
        {
            Task.Run(() =>
                {
                    _rPcServer.Start();
                });
            foreach (var work in _workServerS) work.Start();
        }
    }

}
